import PAGE from '../../utils/middleware/page'
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings'
import store from '../../store/index'
const app = getApp()

Page(PAGE({
    behaviors: [storeBindingsBehavior],
    storeBindings: {
        store,
        fields: {
            needRefresh: 'vehicle.needRefresh'
        },
        actions: {
            updateNeedRefresh: 'vehicle.updateNeedRefresh'
        }
    },
    data: {
        wxUserInfo: null,
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        canIUseGetUserProfile: false,
        canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'), // 如需尝试获取用户信息可改为false
        wxLoginRes: null,
        showGetPhone: false,
        html: null,
        showAgree: false,
        showLogin: false,
        allowLogin: false,
        apiField: {
            module: 'common',
            api: 'GetSetting',
            data: 'html',
            search: { code: 'MemberRegister' }
        }
    },
    async onLoad() {
        this.data.wxLoginRes = await wx.$Fun.wxLogin()
        if (wx.getUserProfile) {
            this.setData({
                canIUseGetUserProfile: true
            })
        }
        var cacheData = wx.getStorageSync('agree')
        if (!cacheData) {
            await this.fetchUseAgree()
        } else {
            this.setData({
                showLogin: true,
                allowLogin: true
            })
        }
    },
    async fetchUseAgree() {
        this.handleFetchData({
            complete: (data) => {
                console.log(data)
                this.setData({
                    showAgree: true
                })
            }
        }, 'apiField', true)
    },
    getUserProfile(e) {
        var that = this
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        wx.getUserProfile({
            desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: async (res) => {
                this.data.wxUserInfo = res.userInfo
                that.login()
            }
        })
    },
    getUserInfo(e) {
        // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
        this.setData({
            loginUserInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    //快捷登录
    async login() {
        if (!this.data.allowLogin) {
            wx.$Fun.showToast('您没勾选同意协议，不能登录.')
            return
        }
        try {
            const res = await wx.$Api.member.Login({
                data: {
                    Code: this.data.wxLoginRes.code
                }
            })
            if (res.Data.Status == 0) {
                //未注册进行注册
                this.setData({
                    showGetPhone: true
                })
            }
            else if (res.Data.Status == 1) {

                //未完善跳转到完善信息页面
                this.getToken(res.Data.Token, () => {
                    wx.$Fun.toPage({
                        page: 'userEdit',
                        params: {
                            pageType: 'redirectTo'
                        }
                    })
                })
            }
            else if (res.Data.Status == 2) {
                //已完善获取token
                this.getToken(res.Data.Token, () => {
                    wx.$Fun.toPage({
                        page: 'mine',
                        params: {
                            pageType: 'switchTab'
                        }
                    })
                })
            }
        }
        catch (e) {
            wx.$Fun.showToast(e.Message)
        }
        finally {
            this.data.wxLoginRes = await wx.$Fun.wxLogin()
        }
    },
    // 注册前先解密手机
    async register(event) {
        if (event.detail.errMsg !== 'getPhoneNumber:ok') return
        try {
            var request = {
                WxCode: this.data.wxLoginRes.code,
                IV: event.detail.iv,
                EncryptedData: event.detail.encryptedData
            }
            const res = await wx.$Api.member.Register({ data: request })
            if (res.Data.Status == 1) {
                //未完善跳转到完善信息页面
                this.getToken(res.Data.Token, () => {
                    this.updateNeedRefresh(true)
                    wx.$Fun.toPage({
                        page: 'userEdit',
                        params: {
                            pageType: 'redirectTo'
                        }
                    })
                })
            }
            else if (res.Data.Status == 2) {
                //已完善获取token
                this.getToken(res.Data.Token, () => {
                    wx.$Fun.toPage({
                        page: 'mine',
                        params: {
                            pageType: 'redirectTo'
                        }
                    })
                })
            }

        } catch (e) {
            wx.$Fun.showToast(e.Message)
        }
        finally {
            this.data.wxLoginRes = await wx.$Fun.wxLogin()
        }
    },
    getToken(token, cb) {

        var _this = this
        wx.setStorage({
            key: 'token',
            data: `bearer ${token.AccessToken}`,
            success() {
                app.globalData.isLogin = true
                _this.updateNeedRefresh(true)
                typeof cb === 'function' && cb()
            }
        })
    },
    handleAgree() {
        wx.setStorageSync('agree', true)
        this.setData({
            showAgree: false,
            showLogin: true,
            allowLogin: true
        })
    },
    checkboxChange(e) {
        var values = e.detail.value
        if (!values || values.length == 0) {
            this.setData({
                allowLogin: false
            })
        }
        else {
            this.setData({
                allowLogin: true
            })
        }
    }
}))